package com.fiidee.blog.service.impl;

import com.fiidee.blog.common.ERRORCODE;
import com.fiidee.blog.dto.BlogDTO;
import com.fiidee.blog.entity.Blog;
import com.fiidee.blog.entity.BlogData;
import com.fiidee.blog.entity.Collection;
import com.fiidee.blog.mapper.BlogDataMapper;
import com.fiidee.blog.mapper.BlogMapper;
import com.fiidee.blog.mapper.CollectionMapper;
import com.fiidee.blog.service.BlogService;
import com.fiidee.blog.service.ConfigService;
import com.fiidee.blog.util.CookieAndSessionUtil;
import com.fiidee.blog.util.DateUtil;
import com.fiidee.blog.util.HtmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * Created by 瑱彬 on 2015/5/27.
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    BlogMapper blogMapper;

    @Autowired
    BlogDataMapper blogDataMapper;

    @Autowired
    CollectionMapper collectionMapper;

    @Autowired
    ConfigService configService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return blogMapper.deleteByPrimaryKey( id);
    }

    @Override
    public int insert(Blog record) {
        return blogMapper.insert(record);
    }

    @Override
    public int insertSelective(Blog record) {
        return blogMapper.insertSelective(record);
    }

    @Override
    public Blog selectByPrimaryKey(Integer id) {
        return blogMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Blog record) {
        return blogMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Blog record) {
        return blogMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Blog> selectByDTO(BlogDTO dto) {
        return blogMapper.selectByDTO(dto);
    }

    @Override
    public int deleteInIds(String ids) {
        return blogMapper.deleteInIds(ids);
    }

    private Blog createBlog(Blog blog , BlogData blogData){
        int nowTime = DateUtil.getNowInt();
        blog.setAddTime(nowTime);
        blog.setHits(0);
        blog.setIsrec(false);
        blog.setUpdateTime(nowTime);
        blog.setThumb(HtmlUtil.findSingleImgsInHtml(blogData.getContent()));
        blog.setBcontent(HtmlUtil.getSummary(blogData.getContent(),configService.getNum("summaryLength")));
        return blog;
    }

    private void setBlogCookie(Blog blog,BlogData blogData,HttpServletResponse response){
        CookieAndSessionUtil.addCookie("catid", blog.getCatid() + "", response);
        CookieAndSessionUtil.addCookie("title", blog.getTitle(), response);
        CookieAndSessionUtil.addCookie("kword", blog.getKword(), response);
        CookieAndSessionUtil.addCookie("bcontent", blog.getBcontent(), response);
        CookieAndSessionUtil.addCookie("tags", blog.getTags(), response);
        CookieAndSessionUtil.addCookie("content", blogData.getContent(), response);
    }

    private void removeBlogCookie(HttpServletResponse response){
        CookieAndSessionUtil.removeCookie("catid", response);
        CookieAndSessionUtil.removeCookie("title", response);
        CookieAndSessionUtil.removeCookie("kword", response);
        CookieAndSessionUtil.removeCookie("bcontent", response);
        CookieAndSessionUtil.removeCookie("tags", response);
        CookieAndSessionUtil.removeCookie("content", response);
    }

    private List<String> separateTags(String tagstr){
        System.out.println(tagstr);
        if("".equals(tagstr) || tagstr == null){
            return null;
        }
        String tags[] = tagstr.split("\\|");
        List<String> tagList = Arrays.asList(tags);
        return  tagList;
    }

    @Override
    public int doPublish(Blog blog, BlogData blogData,HttpServletResponse response) {
        blog = createBlog(blog,blogData);
        blogMapper.insertSelective(blog);
        System.out.println(blog);
        if(0 == blog.getId())
            return ERRORCODE.INSERTERROR;
        blogData.setAid(blog.getId());
        blogDataMapper.insertSelective(blogData);
        System.out.println(blogData);
        removeBlogCookie(response);
        return ERRORCODE.SUCCESS;
    }



    @Override
    public int doSave(Blog blog, BlogData blogData, HttpServletResponse response) {
        setBlogCookie(blog, blogData, response);
        return ERRORCODE.SUCCESS;
    }

    private List<Map<String,Object>> getBlogList(BlogDTO dto ,int page){
        if(0 == page ){
            page = 1;
        }
        //在配置项中没有pageRows配置的时候，默认大小为 10
        int rows = configService.getNum("pageRows");
        int index = (page - 1) * rows;
        String contentDateFormat = configService.getConfig("contentDateFormat");
        List<Map<String,Object>> blogs = blogMapper.selectHomeList(dto,index, rows);

        for(Map<String,Object> blog:blogs){
            int addTime = (Integer)blog.get("addTime");
            int updateTime = (Integer)blog.get("updateTime");
            String addTimeStr = DateUtil.intToString(addTime,contentDateFormat);
            String updateTimeStr = DateUtil.intToString(updateTime,contentDateFormat);

            blog.put("addTime",addTimeStr);
            blog.put("updateTime",updateTimeStr);

            blog.put("tags",separateTags((String)blog.get("tags")));

        }

        return blogs;

    }

    @Override
    public List<Map<String,Object>> getHomeList(int page) {
        return getBlogList(null,page);
    }

    @Override
    public List<Map<String, Object>> getSelfList(int page,int uid) {
        BlogDTO dto = new BlogDTO();
        dto.setStatement("b.userid = "+uid);
        return getBlogList(dto,page);
    }

    @Override
    public List<Map<String, Object>> getCategoryList(int page, int catId) {
        BlogDTO dto = new BlogDTO();
        dto.setStatement("b.catid = " + catId);
        return getBlogList(dto,page);
    }

    @Override
    public List<Map<String, Object>> getUserList(int page, int uid) {
        BlogDTO dto = new BlogDTO();
        dto.setStatement("b.userid = " + uid);
        return getBlogList(dto, page);
    }

    @Override
    public List<Map<String, Object>> getRecommendList() {
        return blogMapper.selectRecommendList();
    }

    @Override
    public Map<String, Object> getArroundBlog(Integer id) {
        return blogMapper.getArroundBlog(id);
    }

    @Override
    public int countHomeList() {
        return blogMapper.countHomeList(null);
    }

    @Override
    public int countCategoryList(int catId) {
        BlogDTO dto = new BlogDTO();
        dto.setStatement("b.catid = "+catId);
        return blogMapper.countHomeList(dto);
    }

    @Override
    public int countUserList( int uid) {
        BlogDTO dto = new BlogDTO();
        dto.setStatement("b.userid = "+uid);
        return blogMapper.countHomeList(dto);
    }

    private Map<String,Object> timestampToTimeStr(Map<String,Object> map){
        map.put("addTime",DateUtil.intToString((int)map.get("addTime"),"yyyy-MM-dd HH:mm:ss"));
        map.put("updateTime",DateUtil.intToString((int)map.get("updateTime"),"yyyy-MM-dd HH:mm:ss"));
        return map;
    }

    @Override
    public Map<String, Object> getBlogContent(int id) {
        Map<String, Object> map = blogMapper.getBlogContent(id);
        map = timestampToTimeStr(map);
        return map;
    }

    private boolean checkPermission(int userid, int blogid){
        Blog blog = blogMapper.selectByPrimaryKey(blogid);
        if(blog.getId() != userid){
            return false;
        }
        return true;
    }

    private int topSwitch(int userid, int blogid, boolean val){
        if(!checkPermission(userid,blogid)){
            return ERRORCODE.NOPERMISSION;
        }
        Blog updateBlog = new Blog();
        updateBlog.setUpdateTime(DateUtil.getNowInt());
        updateBlog.setId(blogid);
        updateBlog.setIsrec(val);
        int result = blogMapper.updateByPrimaryKeySelective(updateBlog);
        if(result == 0){
            return ERRORCODE.UPDATEERROR;
        }else{
            return ERRORCODE.SUCCESS;
        }

    }

    @Override
    public int topBlog(int userid, int blogid) {
        return topSwitch(userid,blogid,true);
    }

    @Override
    public int cancelTopBlog(int userid, int blogid) {
        return topSwitch(userid,blogid,false);
    }


    private int trashSwitch(int userid,int blogid, boolean val){
        if(!checkPermission(userid,blogid)){
            return ERRORCODE.NOPERMISSION;
        }

        Blog updateBlog = new Blog();
        updateBlog.setUpdateTime(DateUtil.getNowInt());
        updateBlog.setId(blogid);
        updateBlog.setTrash(val);
        int result = blogMapper.updateByPrimaryKeySelective(updateBlog);
        if(result == 0){
            return ERRORCODE.UPDATEERROR;
        }else{
            return ERRORCODE.SUCCESS;
        }

    }

    @Override
    public int trashBlog(int userid, int blogid) {
        return trashSwitch(userid,blogid,true);
    }

    @Override
    public int recoveryBlog(int userid, int blogid) {
        return trashSwitch(userid,blogid,false);
    }

    @Override
    public int collectionBlog(int userid, int blogid) {
        Collection collection = new Collection();
        collection.setAddTime(DateUtil.getNowInt());
        collection.setAid(blogid);
        collection.setUserid(userid);

        int result = collectionMapper.insertSelective(collection);
        if(result == 0){
            return ERRORCODE.INSERTERROR;
        }else{
            return ERRORCODE.SUCCESS;
        }

    }

    @Override
    public int cancelCollecttion(int userid, int blogid) {
        return collectionMapper.cancelCollection(userid,blogid);
    }

}
